package school.xauat.inscription_sys.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import school.xauat.inscription_sys.pojo.Bronzeware;
import school.xauat.inscription_sys.pojo.User;
import school.xauat.inscription_sys.pojo.vo.RespVo;
import school.xauat.inscription_sys.service.BronzewareService;
import school.xauat.inscription_sys.service.UserService;

import javax.servlet.http.HttpSession;

import java.util.List;

import static school.xauat.inscription_sys.errorcode.ErrorCode.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zsy
 * @since 2022-05-03
 */
@RestController
@RequestMapping("/inscription_sys/bronzeware")
public class BronzewareController {

    @Autowired
    BronzewareService bronzewareService;

    @Autowired
    UserService userService;

    @PostMapping("/add")
    public RespVo add(@RequestBody Bronzeware bronzeware, HttpSession session) {
        Object obj = session.getAttribute("user");
        if (obj == null) {
            return RespVo.error(ERROR_NO_LOGIN, getMsg(ERROR_NO_LOGIN));
        }
        User user = (User) obj;
        user = userService.getOne(new QueryWrapper<User>().eq("username", user.getUsername()));
        bronzeware.setUserId(user.getId());
        if (!checkAndValid(bronzeware)) {
            return RespVo.error(ERROR_ILLEGAL_PARAMS, getMsg(ERROR_ILLEGAL_PARAMS));
        }
        if (bronzewareService.save(bronzeware)) {
            return RespVo.ok();
        } else {
            return RespVo.error(ERROR_DB_UNKNOWN, getMsg(ERROR_DB_UNKNOWN));
        }
    }

    private boolean checkAndValid(Bronzeware bronzeware) {
        return bronzeware != null
                && bronzeware.getName() != null
                && bronzeware.getInfo() != null
                && bronzeware.getUserId() != null
                && bronzeware.getPicture() != null;
    }

    @GetMapping("/list/{pageNum}")
    public RespVo list(@PathVariable Integer pageNum,
                       @RequestParam(defaultValue = "create_time") String order,
                       HttpSession session) {
        Object obj = session.getAttribute("user");
        if (obj == null) {
            return RespVo.error(ERROR_NO_LOGIN, getMsg(ERROR_NO_LOGIN));
        }
        if (pageNum == null) {
            pageNum = 0;
        }
        int count = bronzewareService.count();
        List<Bronzeware> list = bronzewareService.listBronzeware(pageNum, 5, order);
        int pages = (int) Math.ceil(count / 5);
        return RespVo.obj(new listObj(count, pages, list));
    }

    @Data
    class listObj {
        int count;
        int pages;
        List<Bronzeware> bronzewares;

        public listObj(int count, int pages, List<Bronzeware> bronzewares) {
            this.count = count;
            this.pages = pages;
            this.bronzewares = bronzewares;
        }
    }
}

